#!/usr/bin/python

import os
from mininet.net import Mininet
from mininet.node import RemoteController, Controller, OVSSwitch
from mininet.cli import CLI
from mininet.log import setLogLevel, info
from mininet.link import Intf,TCLink
from mininet.util import dumpNodeConnections
import time

def run(topofile,flow):

    info( "\n*** Connect controllers\n" )
    c0 = RemoteController( 'c0',ip='192.168.230.129', port=6653 )
    net = Mininet( controller=c0, switch=OVSSwitch, link=TCLink,  autoSetMacs=True, autoStaticArp=True )
    
    sw = []
    host = []
    with open(topofile) as fin:      
            numSw_ = fin.readline()
            numSw_ = numSw_.split()
            numSw= int(numSw_[1])
            info("\n*** Add swithes\n")
            for i in range(numSw):
                s = net.addSwitch('s%s'%(i+1))
                sw.append(s)
	    
            numHost_ = fin.readline()
            numHost_ = numHost_.split()
            numHost = int(numHost_[1])
	    

            info("\n*** Add hosts\n")
            for j in range(numHost):
                h = net.addHost('h%s'%(j+1),ip = '10.0.0.%s/24'%(j+1))
                host.append(h)
            
	    fin.readline()
            
	    info( "\n*** Add links\n" )
            for line in fin.readlines():
                line = line.split()
                #print line[0]
		#print line[1]
		#print line[2]
                u = int(line[1])
                v = int(line[2])
                if u < numHost:
                    net.addLink(host[u], sw[v-numHost])
		    #print host[u],sw[v-numHost]
                else:
                    net.addLink(sw[u-numHost], sw[v-numHost], bw=1, delay='0.1ms')
    
    info( "\n*** Add Intf(default eth1)\n" )
    s1 = net.switches[0]
    Intf('eth1',node=s1)
    s1.cmdPrint("dhclient eth1")

    info( "*** Starting network\n" )
    #net.start()
    net.build()
    c0.start()
    for x in net.switches:
        x.start([c0])

    print('\033[1;34;40mDumping host connections\033[0m')
    dumpNodeConnections(net.hosts)
    time.sleep(2)
    
    print("\033[1;34;40mInsert rules\033[0m")
    with open(flow) as fi:
        numflow = int(fi.readline().split()[1])
        fi.readline()
        count = 0
        for line in fi.readlines():
            #print line
            switch = net.switches[int(line.split()[2].split("s")[1])-1]
            #switch.cmdPrint(line.rstrip('\n'))
            count=count+1
        if (count == numflow):
            print("\033[1;34;40mInserted"),
            print(numflow),
            print(" preseted rules !\033[0m")
        else:
            print("\033[1;31;40mThe actual number of rules isn't accord with numRule.Please check the rule file.\033[0m")
            print("\033[1;34;40mInserted "),
            print(count),
            print(" preseted rules !\033[0m")
            
    time.sleep(1)
    CLI(net)
    net.stop()
if __name__ =='__main__':
    setLogLevel( 'info' )  # for CLI output
    print """\033[1;32;40m\n
    topology file: "/home/li/scandir-master/scantopo/testtopo.txt" 
    flowrule file: "/home/li/scandir-master/scantopo/rules/AclRule.txt\033[0m"""
    run("/home/li/scandir-master/scantopo/testtopo.txt", "/home/li/scandir-master/scantopo/rules/AclRule.txt")
